package br.com.localfloripa.listeners;

import javax.el.ELContext;
import javax.faces.FacesException;
import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.localfloripa.controllers.TemplateController;
import br.com.localfloripa.util.StringUtils;

public class TemplatePhaseListener implements PhaseListener {

	private static final Logger log = LoggerFactory.getLogger(TemplatePhaseListener.class);
	private static final String TEMPLATE_PAGE = "faces/site/xhtml/templates/complex-body.xhtml";
	
	@Override
	public void afterPhase(PhaseEvent event) {
		String imobiliaria = event.getFacesContext().getExternalContext().getRequestPathInfo();
		if (imobiliaria != null && StringUtils.occurrenceString(imobiliaria, "/") == 1) {
			FacesContext context = event.getFacesContext();
	        ExternalContext ext = context.getExternalContext();
            Application app = context.getApplication();
            ViewHandler viewHandler = app.getViewHandler();
            
            ELContext elContext = FacesContext.getCurrentInstance().getELContext();
            TemplateController controller = (TemplateController) FacesContext.getCurrentInstance().getApplication()
                .getELResolver().getValue(elContext, null, "templateController");

            HttpServletRequest req = (HttpServletRequest) ext.getRequest();
            req.setAttribute("imobiliaria", imobiliaria.substring(1, imobiliaria.length()));
            controller.loadTemplate();
            
            UIViewRoot view = viewHandler.createView(context, "/" + TEMPLATE_PAGE);
            context.setViewRoot(view);
            context.renderResponse();
            try {
                viewHandler.renderView(context, view);
                context.responseComplete();
            } catch (Throwable t) {
                throw new FacesException("Session timed out", t);
            }	        
		}
	}

	@Override
	public void beforePhase(PhaseEvent event) {
		
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.UPDATE_MODEL_VALUES;
	}

}
